# -*- coding:utf-8 -*-
__author__ = 'xigu007'
from kivy.clock import _default_time as time
from kivy.metrics import dp, sp
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty,ListProperty
from kivy.lang import Builder
from kivy.uix.behaviors.button import ButtonBehavior
from recycleview.staggered_layout import StaggeredViewMixin
from composite_widget.base import RelativeComposite,Division
from composite_widget.content import LabelContent, ImageContent, ShapeContent
from composite_widget.group import ShapeBackground
from composite_widget.animate import register_animate
from random import randint,sample
Builder.load_string('''
<CommentPad>
    canvas.before:
        Color:
            rgb: 1,1,1
        Rectangle:
            pos: 0,0
            size: self.size
        #背景分割线
        Color:
            rgb: 0.75,0.75,0.75
        Rectangle:
            pos: 0,0
            size: self.width,1
    on_release: self.comment_pad_clicked()
    wrap_content_height: True
    Division:
        absolute_width: dp(65)
        ShapeContent:
            id: user_picture
            margin: 0,0,15,15
            ellipse: True
            image_source: root.user_picture
            size_hint: 0.7, None
    Division:
        orientation: 'vertical'
        Division:
            id: vip_container
            contents_typesetting: 'anchor'
            absolute_height: dp(32)
            LabelContent:
                text: root.user_name
                font_size: sp(15)
                color: 0.1, 0.1, 0.8, 1
                anchor: 'left'
                align: 'bottom'
            LabelContent:
                margin: 0,15,0,0
                text: root.comment_time
                font_size: sp(13)
                color: 0.6, 0.6, 0.6, 1
                anchor: 'right'
        Division:
            contents_typesetting: 'anchor'
            absolute_height: dp(30)
            LabelContent:
                text: '打分'
                margin: 0,6,0,0
                font_size: sp(13)
                color: 0.6, 0.6, 0.6, 1
                anchor: 'left'
            ImageContent:
                id: start_1
                image_size: sp(18),sp(18)
                source: './res/start_normal.png'
                anchor: 'left'
            ImageContent:
                id: start_2
                image_size: sp(18),sp(18)
                source: './res/start_normal.png'
                anchor: 'left'
            ImageContent:
                id: start_3
                image_size: sp(18),sp(18)
                source: './res/start_normal.png'
                anchor: 'left'
            ImageContent:
                id: start_4
                image_size: sp(18),sp(18)
                source: './res/start_normal.png'
                anchor: 'left'
            ImageContent:
                id: start_5
                image_size: sp(18),sp(18)
                source: './res/start_normal.png'
                anchor: 'left'
        Division:
            contents_typesetting: 'anchor'
            wrap_content_height:True
            LabelContent:
                text: root.comment
                color: 0.2,0.2,0.2,1
                text_width_hint: 0.95
                line_height: 1.5
                anchor: 'left'
        Division:
            id: image_container
            contents_typesetting: 'doc_flow'
            wrap_content_height:True
        Division:
            contents_typesetting: 'anchor'
            absolute_height: dp(50)
            LabelContent:
                text: '浏览10'
                color: 0.5,0.5,0.5,1
                anchor: 'left'
            LabelContent:
                text: '赞5'
                color: 0.5,0.5,0.5,1
                margin: 3,0,0,0
                anchor: 'left'
            ShapeBackground:
                contents_typesetting: 'anchor'
                color: 0.7,0.7,0.7,1
                radius: 10
                solid: False
                anchor: 'right'
                margin: 0,15,0,0
                auto_size: False
                size: dp(60),dp(26)
                touch_callback: root.comment_touched
                ImageContent:
                    margin: 0,3,0,0
                    size_hint:  None, 0.7
                    source: './res/movie_comment_write.png'
                LabelContent:
                    text: '评论'
                    color: 0.2,0.2,0.2,1
                    font_size: sp(13)
            Group:
                id: zan_group
                contents_typesetting: 'float'
                auto_size: False
                size: dp(60), dp(26)
                margin: 0,15,0,0
                anchor: 'right'
                ShapeBackground:
                    contents_typesetting: 'anchor'
                    color: 0.7,0.7,0.7,1
                    radius: 10
                    solid: False
                    auto_size: False
                    size: dp(60), dp(26)
                    touch_callback: root.zan_touched
                    ImageContent:
                        id: zan_image
                        margin: 0,3,0,0
                        size_hint:  None, 0.7
                        source: './res/movie_collection_gray.png'
                    LabelContent:
                        text: '赞'
                        color: 0.2,0.2,0.2,1
                        font_size: sp(13)
''')

k00_property={'opacity':1.0, 'translate':{'y': 0}, 'scale':{'x':0.8,'y':0.8}, 'time_func':'ease-out'}
k08_property={'opacity':1.0, 'translate':{'y': dp(60)}, 'scale':{'x':1.8,'y':1.8}, 'time_func':'ease-in'}
k10_property={'opacity':0.0,}
zan_animate = {'duration':0.8,  'keyframes':[(0.0,k00_property),(0.8,k08_property), (1.0,k10_property)]}
register_animate('zan_animate', **zan_animate)

class CommentPad(ButtonBehavior, RelativeComposite, StaggeredViewMixin):
    user_picture = StringProperty('')
    user_name = StringProperty('')
    comment_time = StringProperty('2016年6月3日')
    comment = StringProperty('')
    def __init__(self,**kwargs):
        vip_icon = self.vip_content = ImageContent()
        vip_icon.margin = (10,0,0,0)
        vip_icon.image_size= sp(26),sp(26)
        vip_icon.source= './res/vip.png'
        vip_icon.anchor= 'left'
        self.vip_flg = False
        self.score = 5
        self.pictures = []
        self.zan_animate_label = None
        self.t0 = 0
        super(CommentPad,self).__init__(**kwargs)
        self.bind_animate('user_picture', 'swing')

    def comment_pad_clicked(self,*args):
        #print '--comment_pad_clicked-*************'
        self.start_animate('user_picture')


    def zan_touched(self, content, action):
        iamge = self.ids['zan_image']
        if action == 'down':
            iamge.source = './res/icon_like_pressed.png'
        elif action == 'up':
            iamge.source = './res/movie_collection_gray.png'
        elif action == 'release':
            zan_group = self.ids['zan_group']
            if self.zan_animate_label is None:
                label = self.zan_animate_label = LabelContent()
                label.text = '+1'
                label.color = 1.0, 0.4, 0.2, 1.0
                label.center_hint = 0.5,0.8
                label.font_size = sp(22)
                zan_group.add_widget(label)
                self.bind_content_id(label, 'animate_label')
            else:
                if self.zan_animate_label not in zan_group.contents_children:
                    zan_group.add_widget(self.zan_animate_label)
                    self.bind_content_id(self.zan_animate_label, 'animate_label')
            self.bind_animate('animate_label', 'zan_animate')
            self.start_animate('animate_label')

    def comment_touched(self, content, action):
        print 'comment_touche action={}'.format(action)

    def refresh_view_attrs(self, rv, data):
        #print 'refresh_view_attrs={}'.format(data['index'])
        #self.t0 = time()
        if self.zan_animate_label is not None:
            zan_group = self.ids['zan_group']
            zan_group.remove_widget(self.zan_animate_label)
        self.user_name = data['user_name']
        self.user_picture = data['user_picture']
        flg = data['vip']
        self._set_vip(flg)
        score = data['score']
        self._set_score(score)
        self.comment = data['comment']
        if self.pictures is not data['pictures']:
            self.pictures = data['pictures']
            self._set_picture(self.pictures)
        self._changed_flag = True

    #置评论图片
    def _set_picture(self, pictures):
        image_container = self.ids['image_container']
        image_container.clear_contents()
        pic_num = len(pictures)
        for pic in pictures:
            image = ImageContent()
            image.source = pic
            image.anchor = 'left'
            image.margin = 0,10,10,10
            #w = 0.5*(self.width - dp(65) - 2*image.margin[1])
            if pic_num == 1:
                w = dp(130)
            elif pic_num == 2:
                w = dp(100)
            else:
                w = dp(80)
            image.image_size = (w,w)
            image_container.add_widget(image)

    #置评分
    def _set_score(self, score):
        if 0 <= score <=5:
            #if score == 3:
                #import math
                #for i in range(500000):
                #    math.cos(75)*256.23
            if self.score != score:
                self.score = score
                start_normal = './res/start_normal.png'
                start_disable = './res/start_disable.png'
                score_images = [self.ids['start_{}'.format(i+1)] for i in range(5)]
                for i in range(5):
                    if i < score:
                        score_images[i].source = start_normal
                    else:
                        score_images[i].source = start_disable

    #置vip图标
    def _set_vip(self,flg):
        vip_container = self.ids['vip_container']
        if self.vip_flg != flg:
            self.vip_flg = flg
            if flg:
                vip_container.add_widget(self.vip_content)
            else:
                for content in vip_container.contents_children[:]:
                    if isinstance(content, ImageContent):
                        vip_container.remove_widget(content)
                        break

    def compute_height(self, recycleview, index, view_width):
        self.layout(0,ref_size=(view_width, None))
        #self.t_end = time()
        #diff = self.t_end - self.t0
        #if diff > 0.03:
        #print 'create comment pad timespan={}'.format(diff)
        return self.height


_s_user_info = [('吃遍江湖','./res/thumb-4.jpg', True),\
                ('池边浆糊','./res/thumb-6.jpg', True),\
                ('宝宝爱吃鱼','./res/thumb-8.jpg', True),\
                ('安如少年终如梦','./res/thumb-9.jpg', True),\
                ('凤凰花开','./res/thumb-10.jpg', True),\
                ('帅气','./res/thumb-11.jpg', True),\
                ('DPUser_1987','./res/tabimage2.png', False),\
                ('DPUser_4096','./res/tabimage3.png', False),\
                ('DPUser_2016','./res/tabimage5.png', False)]

_s_comment = ['大众点评网于2003年4月成立于上海。大众点评是中国领先的本地生活信息及交易平台，也是全球最早建立的独立第三方消费点评网站。',\
              '对吃货来说真是好地方啊',\
              '为啥美队阻止tony报父仇啊，精神病杀人也就能脱罪我觉得法理不通啊！',\
              '没有神盾局研究魔方和法杖，就不会有外星人和奥创等事件，无辜的人就不会死，本来改检讨的是政府，却让复仇者们背了黑锅，其实剧中最可怜的是钢铁侠，他失去亲人，爱人，朋友，却没有人站在他的立场想一下。',\
              '什么鬼地方，浪费我滴金钱时间']

_s_pictures = ['./res/price-img-1.jpg','./res/price-img-2.jpg', './res/price-img-3.jpg',\
               './res/music-player1.png','./res/music-player2.png','./res/music-player3.png']

def generate_comments(num = 100):
    data = []
    for j in range(num):
        i = j % 9
        s_num = randint(0,5)
        pictures = sample(_s_pictures, s_num)
        #pictures = _s_pictures[-2:]
        #print pictures
        data.append({'index':j, 'viewclass':'CommentPad', 'user_name':_s_user_info[i][0], 'user_picture':_s_user_info[i][1],\
                      'vip':_s_user_info[i][2], 'score': randint(0,5),'pictures':pictures, 'comment':_s_comment[i%4]}) #randint(0,5) _s_comment[i%4]
    #data.append({'index':2, 'viewclass':'MyButton'}) randint(0,5)
    return data


if __name__ == '__main__':
    from kivy.clock import Clock
    from kivy.app import App
    from kivy.uix.widget import Widget
    from kivy.uix.label import Label
    from kivy.uix.button import Button
    from  kivy.uix.boxlayout import BoxLayout
    from kivy.uix.gridlayout import GridLayout
    from kivy.uix.boxlayout import BoxLayout
    from kivy.uix.scrollview import ScrollView
    from kivy.uix.floatlayout import FloatLayout
    from kivy.metrics import sp
    from kivy.core.text import LabelBase
    from kivy.resources import resource_add_path
    import os
    LabelBase.get_system_fonts_dir()
    resource_add_path('../fonts')
    os.environ['KIVY_VALID_FONT'] = 'SourceHanSansCN-Regular.otf'
    class MyApp(App):
        def frames_loop(self, dt):
            #print Clock.frames
            if self.t0 > 0:
                self.counter += 1
                if self.counter == 2:
                    t_end = time()
                    print 'frames timespan={}'.format(t_end - self.t0)
                    print 'render timespan={}'.format(t_end - self.create_tm)
                    self.t0  = 0
                    self.counter = 0

        def build(self):
            self.t0 = 0
            self.counter = 0
            self.container = GridLayout(cols=1,margin=dp(5),size_hint_y=None,spacing=8)
            scrollview = ScrollView(do_scroll_x=False)
            scrollview.add_widget(self.container)
            self.container.bind(minimum_height=self.container.setter('height'))
            layout = BoxLayout(size_hint=(1, None), height=50)
            layout.add_widget(Button(text='create 1', on_release=self._btn_create_composite1))
            layout.add_widget(Button(text='create 1', on_release=self._btn_create_composite2))
            layout.add_widget(Button(text='clear', on_release=self._btn_clear))
            root = BoxLayout(orientation='vertical')
            root.add_widget(scrollview)
            root.add_widget(layout)
            Clock.schedule_interval(self.frames_loop, 0)
            return root

        def _btn_create_composite1(self, *args):
            ref_width = self.container.width
            self.t0 = time()
            data = generate_comments(2)
            i = 0
            for kw in data:
                pad = CommentPad()
                pad.refresh_view_attrs(None, kw)
                pad.compute_height(i, None, ref_width)
                i += 1
                self.container.add_widget(pad)
            self.create_tm = time()
            self.counter = 0
            print 'create 1 comment pad timespan={}'.format(self.create_tm - self.t0)

        def _btn_create_composite2(self, *args):
            pass

        def _btn_clear(self, *args):
            self.container.clear_widgets()

    MyApp().run()

